# controllers/approval_controller.py
from flask import Blueprint, request, jsonify
from services.approval_service import ApprovalService
from utils.exceptions import WorkflowException

approval_bp = Blueprint('approval', __name__)


@approval_bp.route('/approvals', methods=['POST'])
def process_approval():
    '''审批处理'''
    try:        
        data = request.json
        user_id = data['user_id']
        instance_id = data['instance_id']
        if not ApprovalService.is_approver_userid(instance_id, user_id):
            raise WorkflowException("您不是当前步骤的审批人")
        ApprovalService.process_approval(
            data['instance_id'],
            data['user_id'],
            data['decision'],
            data.get('comment', '')
        )
        return jsonify({"message": "审批处理成功"}), 200
    except Exception as e:
        raise WorkflowException(str(e), code=400)


@approval_bp.route('/get_pending_approvals', methods=['GET'])
def get_pending_approvals():
    '''获取待审批列表'''
    try:
        user_id = request.args.get('user_id', type=int)
        page_number = request.args.get('page_number', type=int)
        page_size = request.args.get('page_size', type=int)
        
        # user = User.query.get(user_id)
        # if not user:
        #     raise WorkflowException("用户不存在")
        
        pending_instances = ApprovalService.get_pending_approvals(user_id, page_number, page_size)
        result = [{
            "instance_id": item.instance_id,
            "template_name": item.template_name,
            "current_step": item.step_order,
            "form_data": item.form_data,
            "initiator": getattr(item, 'initiator_name', user_id),
            "created_time": item.created_at.isoformat()
        } for item in pending_instances]

        return jsonify({
            "count": len(result),
            "results": result
        }), 200
    except Exception as e:
        raise WorkflowException(str(e), code=400)
